package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

     //过滤器
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /*
        1.获取当前请求的URI
        2.去判断该请求是否需要处理
        3.不需要处理的直接放行,
        4需要处理的看看是否已经登录,如果已经
        登录,则直接放行
        5.未登录返回一个未登录的结果
         */

        log.info("拦截了那个请求:{}",request.getRequestURI());
        String requestURI = request.getRequestURI();

        //需要放行的路径名
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        //定义方法去判断是否需要处理
        boolean check = check(requestURI, urls);
        if (check){
            log.info("不需要处理");
            filterChain.doFilter(request, response);
            return;
        }
         if (request.getSession().getAttribute("employee") !=null){
             //说明已经登录 放行
             log.info("已登录",request.getSession().getAttribute("employee"));

             Long empId = (Long) request.getSession().getAttribute("employee");
             BaseContext.setCurrentId(empId);

             filterChain.doFilter(request, response);
             return;
         }
        log.info("未登录");
         response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
         return;
    }

    private boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
